#!/usr/bin/env bash
#! Encoding UTF-8

LISTEN_PORT=8080

info(){
    echo "$(date +'%F %T') [INFO] " "$@"
}
waring(){
    echo "$(date +'%F %T') [WARING] " "$@"
}
fatal(){
    echo "$(date +'%F %T') [ERROR] " "$@"
    exit 1
}

DATE=$(date +"%a, %d %b %Y %H:%M:%S %Z")
declare -a RESPONSE_HEADERS=(
      "Date: ${DATE}"
   "Expires: ${DATE}"
    "Server: Demo Http Server"
)

add_response_header() {
   RESPONSE_HEADERS+=("$1: $2")
}

http_header_ok(){
    #add_response_header "Content-Type" "text/html"
    #add_response_header "Content-Type" "text/plain"
    echo -e "HTTP/1.1 200 OK\r\n"
    echo "Content-Type text/plain\r\n"
    echo 
    for i in "${RESPONSE_HEADERS[@]}"; do
      echo "$i"
   done
}

HTTP(){
    while true; do 
        {
            http_header_ok
            info $1 
            info $2 
            info $@
        } | nc -lp ${LISTEN_PORT} 
    done
}

HTTP & pid1="$!" # 启动第一个业务进程并记录 pid
info "http started with pid $pid1"

handle_sigterm() {
  info "Received SIGTERM $@"
  kill -SIGTERM $pid1  # 传递 SIGTERM 给业务进程
  wait $pid1  # 等待所有业务进程完全终止
}

handle_sigterm_kill() {
  info "Received SIGKILL $@"
  kill -SIGKILL $pid1  # 传递 SIGTERM 给业务进程
  wait $pid1  # 等待所有业务进程完全终止
}

trap handle_sigterm SIGTERM # 捕获 SIGTERM 信号并回调 handle_sigterm 函数
trap handle_sigterm SIGKILL

wait # 等待回调执行完，主进程再退出